package com.xgpro.pc.studycentre.service.impl;

import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.xgpro.common.enums.ResultCodeEnum;
import com.xgpro.common.exceptions.BusinessRuntimeException;
import com.xgpro.common.service.BaseService;
import com.xgpro.common.utils.ExcelUtils;
import com.xgpro.domain.studycentre.entity.DaiTuTea;
import com.xgpro.domain.studycentre.entity.Edu;
import com.xgpro.domain.studycentre.entity.Tea;
import com.xgpro.domain.studycentre.vo.*;
import com.xgpro.domain.talentintroduction.entity.User;
import com.xgpro.domain.talentintroduction.vo.UserInfo;
import com.xgpro.mapper.studycentre.EduMapper;
import com.xgpro.mapper.studycentre.TeaMapper;
import com.xgpro.mapper.talentintroduction.UserMapper;
import com.xgpro.pc.studycentre.service.TeaPCService;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.multipart.MultipartFile;
import sun.reflect.annotation.ExceptionProxy;
import tk.mybatis.mapper.entity.Example;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;


/**
 * @author tx
 * @version 1.0
 * @date 2019/10/15 22:29
 */
@Service
@Transactional(readOnly = false)
public class TeaPCServiceImpl extends BaseService implements TeaPCService {

    /**
     * 内部导师
     */
    private static final Integer INNERTYPE=0;

    /**
     * 外部导师
     */
    private static final Integer OUTTYPE=1;

    @Resource
    private TeaMapper teaMapper;
    @Resource
    private EduMapper eduMapper;
    @Resource
    private UserMapper userMapper;

    /**
     * 查询导师信息
     * @param teaFront
     * @return
     */
    @Override
    public TeaPCResult qryTeaPCResult(TeaPCFront teaFront) {
        PageHelper.startPage(teaFront.getPage(),teaFront.getPageSize());
        Page<TeaPCBack> pageList=(Page<TeaPCBack>)teaMapper.selectTeaPCList(teaFront.getName(),teaFront.getTeaType(),teaFront.getDeptName(),teaFront.getIsGood());
        TeaPCResult teaPCResult = new TeaPCResult();
        if(pageList!=null){
            teaPCResult.setTeaPCBacks(pageList.getResult());
            teaPCResult.setTotals(pageList.getTotal());
        }
        return teaPCResult;
    }

    /**
     * 新增内部导师
     * @param innerTea
     * @return
     */
    @Override
    public Integer insertInnerTea(InnerTea innerTea) {
        Tea tea = new Tea();
        Integer userId = innerTea.getUserId();
        User user = userMapper.selectByPrimaryKey(userId);
        Example example = new Example(Tea.class);
        Example.Criteria criteria = example.createCriteria();
        criteria.andEqualTo("userId",userId);
        List<Tea> teas = teaMapper.selectByExample(example);
        if(teas!=null&&teas.size()>0){
            throw new BusinessRuntimeException(ResultCodeEnum.HAD_TEA.getCode(),ResultCodeEnum.HAD_TEA.getMessage());
        }
        tea.setJobTitle(user.getJobTitle());
        tea.setAchievement(innerTea.getAchievement());
        tea.setHonorTitle(innerTea.getHonorTitle());
        tea.setTeaYear(innerTea.getTeaYear());
        tea.setUserId(userId);
        tea.setTeaType(INNERTYPE);
        return teaMapper.insert(tea);
    }

    /**
     * 修改内部导师
     * @param innerTea
     * @return
     */
    @Override
    public Integer updateInnerTea(InnerTea innerTea) {
        Tea tea = new Tea();
        tea.setId(innerTea.getId());
        tea.setJobTitle(innerTea.getJobTitle());
        tea.setAchievement(innerTea.getAchievement());
        tea.setHonorTitle(innerTea.getHonorTitle());
        tea.setTeaYear(innerTea.getTeaYear());
        return teaMapper.updateByPrimaryKeySelective(tea);
    }


    /**
     * 外部导师录入
     * @param outTea
     * @return
     */
    @Override
    public Integer insertOutTea(OutTea outTea) {
        Integer eduKind = outTea.getEduKind();
        String school = outTea.getSchool();
        Edu edu = new Edu();
        edu.setSchool(school);
        edu.setEduKind(eduKind);
        eduMapper.insertSelective(edu);
        Integer eduId = edu.getId();
        User user = new User();
        user.setUsername(outTea.getUsername());
        user.setEduId(eduId);
        userMapper.insertSelective(user);
        Integer userId = user.getId();
        Tea tea = new Tea();
        tea.setJobTitle(outTea.getJobTitle());
        tea.setHonorTitle(outTea.getHonorTitle());
        tea.setAchievement(outTea.getAchievement());
        tea.setUserId(userId);
        tea.setTeaYear(outTea.getTeaYear());
        tea.setTeaType(OUTTYPE);
        return teaMapper.insertSelective(tea);
    }

    @Override
    public Integer updateOutTea(OutTea outTea) {
        Integer id = outTea.getId();
        Tea teaDB = teaMapper.selectByPrimaryKey(id);
        Integer userIdDB = teaDB.getUserId();
        User userDB = userMapper.selectByPrimaryKey(userIdDB);
        Integer eduDB = userDB.getEduId();
        Integer eduKind = outTea.getEduKind();
        String school = outTea.getSchool();
        Edu edu = new Edu();
        edu.setSchool(school);
        edu.setEduKind(eduKind);
        edu.setId(eduDB);
        eduMapper.updateByPrimaryKeySelective(edu);
        User user = new User();
        user.setUsername(outTea.getUsername());
        user.setId(userIdDB);
        userMapper.updateByPrimaryKeySelective(user);
        Tea tea = new Tea();
        tea.setJobTitle(outTea.getJobTitle());
        tea.setHonorTitle(outTea.getHonorTitle());
        tea.setAchievement(outTea.getAchievement());
        tea.setTeaYear(outTea.getTeaYear());
        tea.setId(id);
        return teaMapper.updateByPrimaryKeySelective(tea);
    }


    /**
     * 根据id删除
     * @param id
     * @return
     */
    @Override
    public Integer deleteTeaById(Integer id) {
        return teaMapper.deleteByPrimaryKey(id);
    }

    /**
     * 批量删除
     * @param ids
     * @return
     */
    @Override
    public Integer deleteTeaByIds(List<Integer> ids) {
        return teaMapper.deleteTeaByIds(ids);
    }

    /**
     * 外部导师查询
     * @param teaName
     * @return
     */
    @Override
    public List<Map> qryTeaBySelect(String teaName) {
        return teaMapper.qryTeaBySelect(teaName);
    }

    @Override
    public List<User> qryUserBySelect(String userName) {
        Example example = new Example(User.class);
        Example.Criteria exampleCriteria = example.createCriteria();
        if (!"".equals(userName) && null !=userName ){
            userName = userName +"%";
            exampleCriteria.andLike("username",userName);
        }
        exampleCriteria.andIsNotNull("deptId");
        List<User> users = userMapper.selectByExample(example);
        return users;
    }

    /**
     * 导入内部导师
     * @param multipartFile
     * @return
     */
    @Override
    public String importTea(MultipartFile multipartFile) {
        Integer count=0;
        List<List<Object>> bankListByExcel=new ArrayList<List<Object>>();
        try{
            bankListByExcel= ExcelUtils.getBankListByExcel(multipartFile.getInputStream(), multipartFile.getOriginalFilename());
        }catch (Exception e){
            throw new BusinessRuntimeException(ResultCodeEnum.EXCEL_ERROR.getCode(),ResultCodeEnum.EXCEL_ERROR.getMessage());
        }
        if(bankListByExcel.size()<1){
            throw new BusinessRuntimeException(ResultCodeEnum.EXCEL_EMPTY.getCode(),ResultCodeEnum.EXCEL_EMPTY.getMessage());
        }
        ArrayList<Tea> teaList = new ArrayList<Tea>();
        Tea tea=null;
        for (int i=0;i<bankListByExcel.size();i++) {
            List<Object> objects = bankListByExcel.get(i);
            tea=new Tea();
            tea.setTeaType(0);
            if(!"空值".equals((String)objects.get(2))){
                tea.setJobTitle((String)objects.get(2));
            }
            if(!"空值".equals((String)objects.get(3))){
                tea.setHonorTitle((String)objects.get(3));
            }
            if(!"空值".equals((String)objects.get(4))){
                tea.setAchievement((String)objects.get(4));
            }
            tea.setDdId((String)objects.get(5));
            teaList.add(tea);
        }
        List<String> ddIds = teaList.stream().map(x -> x.getDdId()).collect(Collectors.toList());
        Example example = new Example(User.class);
        example.createCriteria().andIn("userId",ddIds);
        List<User> users = userMapper.selectByExample(example);
        for (Tea tea1 : teaList) {
            for (User user : users) {
                if(tea1.getDdId().equals(user.getUserId())){
                    tea1.setUserId(user.getId());
                }
            }
        }
        List<Integer> userIds = users.stream().map(x -> x.getId()).collect(Collectors.toList());
        List<Integer> hadTea=new ArrayList<Integer>();
        if(userIds.size()>0){
            example=new Example(Tea.class);
            example.createCriteria().andIn("userId",userIds);
            List<Tea> teas = teaMapper.selectByExample(example);
            if(teas.size()>0){
                hadTea = teas.stream().map(x -> x.getUserId()).collect(Collectors.toList());
            }
        }
        List<Integer> finalHadTea=hadTea;
        List<String> updateDDids=new ArrayList<String>();
        if(hadTea.size()>0){
            example=new Example(User.class);
            example.createCriteria().andIn("id",hadTea);
            updateDDids = userMapper.selectByExample(example).stream().map(x -> x.getUserId()).collect(Collectors.toList());
        }
        List<String> findUpdateDDids=updateDDids;
        if(updateDDids.size()>0){
            List<Tea> updateTeaList = teaList.stream().filter(x -> findUpdateDDids.contains(x.getDdId())).collect(Collectors.toList());
            for (Tea tea1 : updateTeaList) {
                example=new Example(Tea.class);
                example.createCriteria().andEqualTo("userId",tea1.getUserId());
                teaMapper.updateByExampleSelective(tea1,example);
                count++;
            }
        }
        List<Integer> importUserId = userIds.stream().filter(x -> !finalHadTea.contains(x)).collect(Collectors.toList());
        List<String> hadDDids=new ArrayList<String>();
        if(importUserId.size()>0){
            example=new Example(User.class);
            example.createCriteria().andIn("id",importUserId);
            hadDDids = userMapper.selectByExample(example).stream().map(x -> x.getUserId()).collect(Collectors.toList());
        }
        List<String> finlHadDDis=hadDDids;
        if(hadDDids.size()>0){
            List<Tea> importTeaList = teaList.stream().filter(x -> finlHadDDis.contains(x.getDdId())).collect(Collectors.toList());
            for (Tea tea1 : importTeaList) {
                Integer userId = tea1.getUserId();
                example=new Example(Tea.class);
                example.createCriteria().andEqualTo("userId",userId);
                List<Tea> teas=teaMapper.selectByExample(example);
                if(teas.size()>0){
                    break;
                }
                teaMapper.insertSelective(tea1);
                count++;
            }
        }
        Integer fail=bankListByExcel.size()-count;
        if(fail>0){
            return "成功导入："+count+"条,失败"+fail+"条";
        }
        return  "成功导入："+count+"条";
    }




}
